package com.shuimutong.gmq.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.shuimutong.gmq.server.bean.dos.ObjCacheDo;
import com.shuimutong.gmq.server.dao.ObjCacheDao;
import com.shuimutong.gmq.server.exception.DaoException;
import com.shuimutong.gmvc.annotation.XRepository;
import com.shuimutong.gutil.common.GUtilCommonUtil;

@XRepository
public class ObjCacheDaoImpl extends BaseDao<ObjCacheDo, Long> implements ObjCacheDao {
	
	@Override
	public void add(String objId, String parentObjId, String content, long expireMs) throws DaoException {
		ObjCacheDo objCache = new ObjCacheDo();
		objCache.setObjId(objId);
		objCache.setParentObjId(parentObjId);
		objCache.setContent(content);
		objCache.setCreateTime(System.currentTimeMillis());
		objCache.setExpireMs(expireMs);
		try {
			super.add(objCache);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	@Override
	public void add(String objId, String parentObjId, String content) throws DaoException {
		ObjCacheDo objCache = new ObjCacheDo();
		objCache.setObjId(objId);
		objCache.setParentObjId(parentObjId);
		objCache.setContent(content);
		objCache.setCreateTime(System.currentTimeMillis());
		try {
			super.add(objCache);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	@Override
	public void addOrUpdate(String objId, String content) throws DaoException {
		ObjCacheDo objCache = findByObjId(objId);
		if(objCache != null) {
			objCache.setContent(content);
			try {
				super.update(objCache);
			} catch (Exception e) {
				throw new DaoException(e);
			}
		} else {
			add(objId, "", content);
		}
	}
	
	@Override
	public ObjCacheDo findByObjId(String objId) throws DaoException {
		ObjCacheDo res = null;
		String sql = "select id, obj_id, parent_obj_id, content, create_time, expire_ms from obj_cache where obj_id=?";
		try {
			List<ObjCacheDo> list = super.list(sql, objId);
			if(!GUtilCommonUtil.checkListEmpty(list)) {
				res = list.get(0);
			}
		} catch (Exception e) {
			throw new DaoException(e);
		}
		return res;
	}
	
	@Override
	public List<ObjCacheDo> findByParentObjId(String parentObjId) throws DaoException {
		List<ObjCacheDo> list = new ArrayList();
		String sql = "select id, obj_id, parent_obj_id, content, create_time, expire_ms from obj_cache where parentObjId=?";
		try {
			list = super.list(sql, parentObjId);
		} catch (Exception e) {
			throw new DaoException(e);
		}
		return list;
	}

	@Override
	public void delByObjId(String objId) throws DaoException {
		String sql = "delete from obj_cache where obj_id=?";
		try {
			super.getSqlExecutor().update(sql, new Object[] {objId});
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
}
